﻿<template>
  <div class="faceGroup-container">
    <!-- //Code Gen QueryStart !don't delete -->
    <el-collapse accordion v-model="activeName">
	  <el-collapse-item name="1">
	    <template #title>
	      <el-tag  effect="light" type="warning" round>功能面板</el-tag><el-icon class="header-icon ml12">
	        <info-filled />
	      </el-icon>
	    </template>
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-if="props.info.id==undefined||props.info.id<=0" class="mt8 ml2">
        <el-form-item label="关键字">
          <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字" @keyup.enter.native="handleQuery"/>
          
        </el-form-item>
        <el-form-item label="人臉分組唯一碼">
          <el-input v-model="queryParams.indexCode" clearable="" placeholder="请输入人臉分組唯一碼" @keyup.enter.native="handleQuery"/>
          
        </el-form-item>
        <el-form-item label="分組名稱">
          <el-input v-model="queryParams.name" clearable="" placeholder="请输入分組名稱" @keyup.enter.native="handleQuery"/>
          
        </el-form-item>
        <el-form-item label="分組描述">
          <el-input v-model="queryParams.description" clearable="" placeholder="请输入分組描述" @keyup.enter.native="handleQuery"/>
          
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary"  icon="ele-Search" @click="handleQuery" v-auth="'faceGroup:page'"> 查询 </el-button>
            <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
            
          </el-button-group>
          
        </el-form-item>
      </el-form>
        <el-col :span="24">
         <!-- //Code Gen Start Button1 !don't delete -->
        <el-form-item>
          <el-button type="primary" icon="ele-Plus" @click="openAddFaceGroup" v-auth="'faceGroup:add'">新增</el-button>
          <el-button type="primary" icon="ele-FolderOpened" @click="exportFaceGroup" v-auth="'faceGroup:export'">導出</el-button>
          <el-button type="primary" icon="ele-Download" @click="downLoadTemplate" v-auth="'faceGroup:templateDown'">下載導入模板</el-button>
          <el-button type="primary" icon="ele-UploadFilled" @click="openUploadDialog" v-auth="'faceGroup:import'">導入</el-button>
         
        </el-form-item>
        <!-- //Code Gen End Button1 !don't delete -->
        </el-col>
        
      	</el-collapse-item>
	  </el-collapse>
     <!-- //Code Gen QueryEnd !don't delete -->
    <el-card class="full-table" shadow="hover" style="margin-top: 8px">
      <el-table
				:data="tableData"
				style="width: 100%"
				v-loading="loading"
				tooltip-effect="light"
				row-key="id"
				border=""
                ref="multipleTableRef" 
                :row-class-name="tableRowClassName"
                @sort-change="(column)=>{
				  tableParams.order =column.order;
				  tableParams.field =column.prop;
				  handleQuery();
				}"
                :row-style="rowStyleDisplay"
				 show-summary
                @select-all="(checkList)=>{
					multipleSelection=checkList;
				}"
                :summary-method="getSummaries"
				:cell-style="handleChangeCellStyle"
                @select="handleSelectionChange" :expand-row-keys="expandList"
				@expand-change="handleExpandChange">
        <el-table-column type="selection" align="center" :selectable="checkTable"/>
        <el-table-column type="index" label="序号" width="55" align="center">
          <template #default="scope">
       </template>
       </el-table-column>
        <el-table-column   :sortable="sortTableCheck('')" align="center" prop="indexCode" label="人臉分組唯一碼" width="105" show-overflow-tooltip="" >
        </el-table-column>
        <el-table-column   :sortable="sortTableCheck('')" align="center" prop="name" label="分組名稱" width="140" show-overflow-tooltip="" >
        </el-table-column>
        <el-table-column   :sortable="sortTableCheck('')" align="center" prop="description" label="分組描述" width="140" show-overflow-tooltip="" >
        </el-table-column>
        <!-- //Code Gen Start Button2 !don't delete -->
        <el-table-column  label="操作" :width="getWidthByAuths(['faceGroup:save','faceGroup:edit','faceGroup:delete'])" align="center" fixed="right" show-overflow-tooltip="" v-if="auths(['faceGroup:save','faceGroup:edit','faceGroup:delete'])">
          <template #default="scope">
             <el-button type="warning" icon="ele-CircleCheckFilled" @click="saveData(scope.row)" v-auth="'faceGroup:save'">保存</el-button>
             <el-button type="warning" icon="ele-Edit" @click="openEditFaceGroup(scope.row)" v-auth="'faceGroup:edit'">編輯</el-button>
             <el-button type="primary" icon="ele-Delete" @click="delFaceGroup(scope.row)" v-auth="'faceGroup:delete'">刪除</el-button>
            
          </template>
        </el-table-column>
        <!-- //Code Gen End Button2 !don't delete -->
      </el-table>
      <el-pagination
				v-model:currentPage="tableParams.page"
				v-model:page-size="tableParams.pageSize"
				:total="tableParams.total"
				:page-sizes="[10, 20, 50, 100, 200]"
				small=""
				background=""
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
                layout="total, sizes, prev, pager, next, jumper"
	/>
    	<!-- 上面分页加上这个字符串就居中显示了 ->, -->
      <editDialog
        ref="editDialogRef"
        :title="editFaceGroupTitle"
        @reloadTable="handleQuery"
      />
    </el-card>

    		<el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px" append-to-body="true">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
						<ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action=""
					:on-change="handleChange" accept=".xls,.xlsx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>

        <el-dialog v-model="state.dialogInfoVisible" draggable width="1000px" append-to-body="true">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Document /> </el-icon>
					<span>详情</span>
				</div>
			</template>
			<json-viewer :value="JSON.parse(state.dialogInfoContent)" :expand-depth="8"  copyable boxed sort></json-viewer>
		</el-dialog>

  </div>
</template>

<script lang="ts" setup="" name="faceGroup">
  import { InfoFilled } from '@element-plus/icons-vue';
  import { ref,reactive,onMounted,nextTick } from "vue";
  import { useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage,UploadInstance } from "element-plus";
  import _ from 'lodash';
  import { auth,getWidthByAuths,auths } from '/@/utils/authFunction';
  import { downloadByData, getFileName } from '/@/utils/download';
  //import { formatDate } from '/@/utils/formatTime';

  import editDialog from '/@/views/main/faceGroup/component/editDialog.vue'

  import { pageFaceGroup,saveFaceGroup, deleteFaceGroup,exportFaceGroupExcel,importUrl,downLoadTemplate } from '/@/api/main/faceGroup';
  import { SysFile } from '/@/api-services/models';
  import request from '/@/utils/request';
  	const uploadRef = ref<UploadInstance>();
	const state = reactive({
		loading: false,
		fileData: [] as Array<SysFile>,
		queryParams: {
			fileName: undefined,
			startTime: undefined,
			endTime: undefined,
		},
		tableParams: {
			page: 1,
			pageSize: 10,
			total: 0 as any,
		},
		dialogUploadVisible: false,
		dialogPdfVisible: false,
        dialogInfoVisible:false,
        dialogInfoContent:'',
		fileList: [] as any,
		pdfUrl: '',
	});
  const activeName = ref('1');
  const timer=ref<any>();
  const expandList = ref<any>([]);
  const editDialogRef = ref();
  const loading = ref(false);
  const tableData = ref<any>([]);
  const multipleTableRef = ref<InstanceType<typeof ElTable>>();
  const multipleSelection = ref<any>([]);
  const toggleSelection = (rows ?: []) => {
	 multipleTableRef.value.clearSelection()
  }
  const queryParams = ref<any>({});
  const tableParams = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  frontPath:null
  });
  const editFaceGroupTitle = ref("");
  const currenTab=ref<any>({});
   const tabOption =null;
  
  var props = defineProps({
		info: {
		default: {},
	},
  });
    // 页面加载时
  onMounted(async () => {
	  const route=useRoute();
	  tableParams.value.frontPath=route.path;
      handleQuery();
      if(tabOption!=null){
      currenTab.value=tabOption.column[0];
      }

  });
  //是否能排序
  const sortTableCheck=(icCanSort)=>{
     if(icCanSort!=null&&icCanSort!=""&&icCanSort=="Y")
       return true;
     else 
       return false;
  };

  const selectAfter=()=>{
     nextTick(()=>{
        });
	}
    //页签切换
    const handleTabChange =(column)=> {
        currenTab.value = column;
         selectAfter();
    }
  // 勾选框是否禁用

     const checkTable=(row,index)=>{
     if(row.id){
		return true; //不禁用
        }
		return false; //禁用
     };

     //行颜色
      const tableRowClassName = (every) =>
      {
      }

  	// 打开上传页面
	const openUploadDialog = () => {
		state.fileList = [];
		state.dialogUploadVisible = true;
	};

	// 通过onChanne方法获得文件列表
	const handleChange = (file : any, fileList : []) => {
		state.fileList = fileList;
	};

    //保存行编辑的数据
   const saveData=  _.debounce(async function (row) {
		await saveFaceGroup(row);
		await handleQuery();
	}, 1000);
   

    // 查看详情
    const viewDetail =_.throttle(async (row: any,tableName:string,id:number) => {
    	var url = `api/faceGroup/Info/${tableName}/${id}`
    	var res = await request({url: url,method: 'get'});
    	state.dialogInfoContent=res.data.result;
    	state.dialogInfoVisible = true;
    },1000);

	// 上传
	const uploadFile = async () => {
		if (state.fileList.length < 1) return;
		var url = importUrl();

		var formData = new window.FormData();
		formData.append('file', state.fileList[0].raw);
		var res = await request(
			{
				url: url,
				method: 'post',
				data: formData,
				headers: { 'Content-Type': 'multipart/form-data' }
			}
		)
		ElMessage.success('上传成功');
		await handleQuery();
		state.dialogUploadVisible = false;
	};

  //导出
    const exportFaceGroup=async()=>{
	   var res =await exportFaceGroupExcel(queryParams.value);
	   var fileName = getFileName(res.headers);
	   downloadByData(res.data as any, fileName);
   };

   //下载模板
   	const downLoadTemplate = async () => {
		var url = downLoadTemplate();
		var res = await request({
			url: url,
			method: 'get',
			responseType: 'blob'
		});
		var fileName = getFileName(res.headers);
		downloadByData(res.data as any, fileName);
	}

  // 查询操作
  const handleQuery = async (parentArgument:any) => {
    timer.value = new Date().getTime();
    loading.value = true;
    if(props.info.id>0){
    //Code Gen Start !don't delete 
     queryParams.value.$TemplateField = props.info.id; //展开行对应的id赋值
    //Code Gen End !don't delete 
    }
    if(parentArgument!=null&&parentArgument!=undefined){
	  if(parentArgument.id==-1){
		 queryParams.value.wCode = parentArgument.id; //此页作为组件，parentArgument父组件传过来的值
	  }else{
		 queryParams.value.wCode = parentArgument.wCode; //此页作为组件，parentArgument父组件传过来的值
	  }
	}
    var res = await pageFaceGroup(Object.assign(queryParams.value, tableParams.value));
    tableData.value = res.data.result?.items ?? [];
    tableParams.value.total = res.data.result?.total;
    loading.value = false;
  };

  // 打开新增页面
  const openAddFaceGroup = () => {
    editFaceGroupTitle.value = '添加人臉分組';
    editDialogRef.value.openDialog({});
  };

  // 打开编辑页面
  const openEditFaceGroup = (row: any) => {
    editFaceGroupTitle.value = '编辑人臉分組';
    editDialogRef.value.openDialog(row);
  };


   	const showKeyValueInfo=(list)=>{
		if(list!=null&&list.length>0){
			if(list[0].label!=undefined){
				return list.map(r => r.label)
			}
		}
		return list;
	}
  

  	const handleExpandChange = (row : any, expandedRows : any) => {
		 timer.value = new Date().getTime();
		if (expandedRows.length) {
			expandList.value = [];
			if (row) {
				expandList.value.push(row.id);
			}
		} else {
			expandList.value = [];
		}
	};

  // 删除
  const delFaceGroup = (row: any) => {
    ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(async () => {
    await deleteFaceGroup(row);
    handleQuery();
    ElMessage.success("删除成功");
  })
  .catch(() => {});
  };

  // 改变页面容量
  const handleSizeChange = (val: number) => {
    tableParams.value.pageSize = val;
    handleQuery();
  };

  // 改变页码序号
  const handleCurrentChange = (val: number) => {
    tableParams.value.page = val;
    handleQuery();
  };

  
   	const handleSelectionChange = (val : []) => {
		multipleSelection.value = val
		if (val.length > 1) {
			let del_row = val.shift();
			multipleTableRef.value.toggleRowSelection(del_row, false);
		}
        multipleSelection.value =multipleSelection.value[0];
        selectAfter();
	}







    //修改行颜色
	const rowStyleDisplay = ({ row, rowIndex }) => {
       return null;
	};
	//修改列颜色	
	const handleChangeCellStyle = ({ row, column, rowIndex, columnIndex }) => {
		
	}


	//显示合计
	interface SummaryMethodProps<T = Product> {
		columns : TableColumnCtx<T>[]
		data : T[]
	}
	const getSummaries = (param : SummaryMethodProps) => {
		const { columns, data } = param
		const sums : string[] = []
		columns.forEach((column, index) => {
          var needCollectFileds=[];
            if(needCollectFileds.length<=0)
             return;

			if (index === 0) {
				sums[index] = '汇总'
				return
			}
            if(needCollectFileds.indexOf(column.property)<0){
              return;
            }
       

			const values = data.map((item) => Number(item[column.property]))
			if (!values.every((value) => Number.isNaN(value))) {
				sums[index] = `合计: ${values.reduce((prev, curr) => {
					const value = Number(curr)
					if (!Number.isNaN(value)) {
						return prev + curr
					} else {
						return prev
					}
				}, 0)}`
			} else {
				sums[index] = ""
			}
		})

		return sums
	}





	//将属性或者函数暴露给父组件
   defineExpose({ handleQuery });
</script>
<style scoped lang='scss'>
@import url('../../../../public/css/iconfont.css');
@import url('../../../../public/css/iconshine.css');
@import url('../../../../public/css/linecolor.css');
/* 隐藏全选按钮 */
::v-deep .el-table th.el-table__cell:nth-child(1) .cell {
  visibility: hidden;
}
</style>

